//
//  main.m
//  China
//
//  Created by Scott on 15/1/7.
//  Copyright (c) 2015年 lanou.3g.com. All rights reserved.
//

#import <Foundation/Foundation.h>

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        
        NSString *file = [NSString stringWithContentsOfFile:@"/Users/dllo/Desktop/省市区/area.txt" encoding:NSUTF8StringEncoding error:nil];
        
        NSArray *line = [file componentsSeparatedByString:@"\n"];
        
        NSMutableArray *china = [NSMutableArray array];
        
        for (int i = 0; i < [line count]; i++) {
            
            if (![line[i] hasPrefix:@" "]) {
                
                // 省
                // 1. 记录省名
                NSString *provinceName = line[i];
                
                // 2. 创建省字典
                NSMutableArray *cities = [NSMutableArray array];
                NSMutableDictionary *province = [NSMutableDictionary dictionaryWithObjectsAndKeys: provinceName, @"省名", cities, @"市", nil];
                
                // 3. 将字典添加到中国的数组中.
                [china addObject:province];
                
            } else if (![line[i] hasPrefix:@"    "]) {
                
                // 市
                // 1. 记录市名
                NSString *cityName = line[i];
                
                // 2. 创建市字典
                NSMutableArray *areas = [NSMutableArray array];
                NSMutableDictionary *city = [NSMutableDictionary dictionaryWithObjectsAndKeys:cityName, @"市名", areas, @"区", nil];
                
                // 3. 找到所在省的市数组
                NSMutableArray *cities = [[china lastObject] objectForKey:@"市"];
                
                // 4. 添加进市字典中
                [cities addObject:city];
                
            } else {
                
                // 区
                // 1. 找到区所在省的市数组
                NSMutableArray *cities = [[china lastObject] objectForKey:@"市"];
                
                // 2. 找到区所在市的区数组
                NSMutableArray *areas = [[cities lastObject] objectForKey:@"区"];
                
                // 3. 添加进区数组中
                [areas addObject:line[i]];
            }
        }
        
        // 输出部分
        NSData *data = [NSJSONSerialization dataWithJSONObject:china options:NSJSONWritingPrettyPrinted error:nil];
        
        NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
        
        NSLog(@"%@", str);
        
    }
    return 0;
}